package api

import (
	__ "api-gateway/basic/proto"
	"api-gateway/handler/request"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
)

func UploadFile(c *gin.Context) {
	var req request.UploadFileReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	file, _ := c1.UploadFile(c, &__.UploadFileRequest{
		FileUuid: req.FileUuid,
		Image:    req.Image,
		Video:    req.Video,
		FileType: int64(req.FileType),
		FileSize: float32(req.FileSize),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"data": file,
	})

}
func FindFile(c *gin.Context) {
	var req request.FindFileReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	file, _ := c1.FindFile(c, &__.FindFileRequest{
		Id: int64(req.FileUuid),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"data": file,
	})
}
func GetFile(c *gin.Context) {
	var req request.GetFileReq
	if err := c.ShouldBind(req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": nil,
		})
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewSrvClient(conn)
	file, _ := c1.GetFile(c, &__.GetFileRequest{

		FileType: int64(req.FileType),
		FileSize: float32(req.FileSize),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": err.Error(),
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"data": file,
	})
}
